package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a03_组合总和3复习1
 * </p>
 *
 * @author flyduck
 * @since 2024/12/31
 */
public class a04_组合总和3复习1 {
    public List<List<Integer>> combinationSum3(int targetCount, int targetSum) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        traversal(result, path, targetCount, targetSum, 0, 1);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int targetCount, int targetSum,
                           int sum,int startIdx){
        if(sum > targetSum){
            return;
        }
        if (path.size() == targetCount) {
            if(sum == targetSum){
                result.add(new ArrayList<>(path));
            }
            return;
        }

        //1,2,3,4,5,6,7,8,9
        //targetCount = 5
        //path.size = 3
        //从1开始可以
        //从8开始可以 9 - (targetCount - path.size) + 1
        for (int i = startIdx; i <= 9 - (targetCount - path.size()) + 1; i++) {
            path.add(i);
            sum = sum + i;
            traversal(result, path, targetCount, targetSum, sum, i + 1);
            path.removeLast();
            sum = sum - i;
        }
    }
}
